let $;
var treeGrid = null, tableId = 'zmn-table';
layui.define(['index', 'form', 'table', 'laytpl', 'laypage', 'layedit', 'laydate', "treeGrid", "treeTable"], function (exports) {
    $ = layui.$;
    let layer = layui.layer;
    let table = layui.table;
    let form = layui.form;
    let layDate = layui.laydate;
    let laypage = layui.laypage;
    let element = layui.element;
    let laytpl = layui.laytpl;
    let treeGrid = layui.treeGrid;
    let formSelects = layui.formSelects;
    /*var data = {parentId: json.vo.parentId};*/
    let tab_all = 'ele-div-tab';
    let servCategIds = json.coupBatch.servCategIds;
    let categOneIds = json.coupBatch.categOneIds;
    let categIds = json.coupBatch.categIds;
    let productIds = json.coupBatch.productIds;
    let companyId;
    let cityIds;
    let channelIds;

    let expiryType;
    var treeTable = layui.treeTable;


    //窗口关闭回调
    function endCallback() {
        layui.$("#query-submit").click();
    }

    var layid = location.hash.replace(/^#target=/, '');
    element.tabChange('ele-div-tab', layid);
    //监听Tab切换，以改变地址hash值
    element.on('tab(ele-div-tab)', function (data) {
        location.hash = 'target=' + this.getAttribute('lay-id');
    });
    //重新渲染tabs
    element.render('tab', 'ele-div-tab');

    /**
     * 新增活动
     **/
    $(document).on('click', '#base-info-next-tab', function (obj) {
        element.tabChange(tab_all, 'title-batch-receive');
    });
    //  form.on('submit(base-info-next-tab)', function (obj) {
    //     element.tabChange(tab_all, 'title-batch-receive');
    //     // $("base-receive-next-tab").attr("lay-submit",'');
    // });
    $(document).on('click', '#base-receive-prev-tab', function () {
        element.tabChange(tab_all, 'title-batch-base');
    });
    $(document).on('click', '#base-receive-next-tab', function () {
        element.tabChange(tab_all, 'title-batch-use');
    });
    $(document).on('click', '#base-use-prev-tab', function () {
        element.tabChange(tab_all, 'title-batch-receive');
    });
    $(document).on('click', '#base-use-next-tab', function () {
        element.tabChange(tab_all, 'title-batch-cost-share');
    });
//     form.on('submit(base-use-next-tab)', function (obj) {
//         element.tabChange(tab_all, 'title-batch-cost-share');
//     });
    $(document).on('click', '#base-share-prev-tab', function () {
        element.tabChange(tab_all, 'title-batch-use');
    });
    $(document).on('click', '#base-share-next-tab', function () {
        element.tabChange(tab_all, 'title-batch-use-range');
    });
    $(document).on('click', '#base-range-prev-tab', function () {
        element.tabChange(tab_all, 'title-batch-cost-share');
    });


    // 表单提交
    form.on('submit(zmn-batch-form-use-submit)', function (obj) {

        var param = obj.field;
        var isverifySuccess = verifyParam(param);
        if (!isverifySuccess) {
            return false;
        }
        let cityValues = json.coupBatch.cityIds;
        let companyValues = formSelects.value('companyTypeSelect');
        let channelValues = formSelects.value('channelTypeSelect');
        let companyIdArray = new Array();
        let cityIdArray = new Array();
        let channelArray = new Array();
        $(cityValues).each(function (index, item) {
            let cityId = parseInt(item);
            if (cityIdArray.indexOf(cityId) <= -1) {
                cityIdArray.push(cityId);
            }
        });
        $(companyValues).each(function (index, item) {
            let companyId = parseInt(item.value);
            if (companyIdArray.indexOf(companyId) <= -1) {
                companyIdArray.push(companyId);
            }
        });
        $(channelValues).each(function (index, item) {
            let channelId = parseInt(item.value);
            if (channelArray.indexOf(channelId) <= -1) {
                channelArray.push(channelId);
            }
        });


        if (companyIdArray.length == 0) {
            layer.msg("请选择公司条件");
            return false;
        }

        if (json.coupBatch.servCategIds == null || json.coupBatch.servCategIds.length < 1) {
            layer.msg("请选择品类条件");
            return false;
        }

        if (cityIdArray.length == 0) {
            layer.msg("请选择城市条件");
            return false;
        }

        if (channelArray.length == 0) {
            layer.msg("请选择渠道条件");
            return false;
        }

        /*if (zmnUtil.isEmptyNull(param.receiveChannel)) {
            layer.msg("领取渠道不能为空");
            return false;
        }*/

        param.servCategIds = json.coupBatch.servCategIds;
        param.categOneIds = json.coupBatch.categOneIds;
        param.categIds = json.coupBatch.categIds;
        param.productIds = json.coupBatch.productIds;
        param.companyIds = companyIdArray;
        param.cityIds = cityIdArray;
        param.channelIds = channelArray;
        param.costDeptId = json.deptId;
        param.costDeptName = json.deptName;
        var apportionRate = JSON.parse(param.apportionRate);
        param.headOfficeRate = parseInt(apportionRate[0].value);
        param.infoCompanyRate = parseInt(apportionRate[1].value);
        param.masterRate = parseInt(apportionRate[2].value);
        var apportionChannelRate = JSON.parse(param.apportionChannelRate);
        param.channelRate=parseInt(apportionChannelRate[0].value);
        if (param.note && param.note.length > 200) {
            layer.msg("备注不能超过200字符");
            return false;
        }
        //是否全选
        if (param.channelIds.length == json.channelType.length) {
            //全选
            param.channelSelectedType = 2;
        }
        else {
            //没全选
            param.channelSelectedType = 1;
        }
        param.citySelectedType = 2;
        param.productSelectedType = 2;
        // 检查服务产品参数
        // if (!servCategIds){
        //     layer.msg("请选择服务条件");
        //     return false;
        // } else {
        //     param.servCategIds = servCategIds;
        //     param.categOneIds = categOneIds;
        //     param.categIds = categIds;
        //     var productCheckData = table.checkStatus('zmn-product-table').data;
        //     if (productCheckData.length > 0){
        //         var arr = new Array();
        //         for (var i = 0;i<productCheckData.length;i++){
        //             arr.push(productCheckData[i].value)
        //         }
        //         param.productIds = arr;
        //     }else if (productIds) {
        //         param.productIds = productIds;
        //     }
        // }
        // if (!param.activateWay) {
        //     layer.msg("请选择激活方式");
        //     return false;
        // }
        if (param.preferentialType == 1) {
            param.preferentialValueFormat = param.preferentialDiscountValue;
        }
        else {
            param.preferentialValueFormat = param.preferentialValue;
        }
        param.salePriceFormat = param.salePrice;
        param.conditionFormat = param.condition;
        param.preferentialValue = null;
        param.salePrice = null;
        param.condition = null;
        if (json.coupBatch.batchId) {
            param.batchId = json.coupBatch.batchId;
        }
        //  layer.msg("校验通过");
        $("#submit").prop("disabled", true);
        $.ajax({
            type: "POST",
            url: "/coup/batch/addEdit.action",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(param),
            success: function (json) {
                if (json.status == 200) {
                    zmnLayUtil.closeThisIframeMsg(parent, json.message, "zmn-coup-table");
                    parent.location.reload(true);
                }
                layer.msg(json.message);
            }
        });
        $("#submit").prop("disabled", false);
        return false;
    });

    /**
     * 校验
     */
    function verifyParam(param) {
        // 优惠批次信息
        if (zmnUtil.isEmptyNull(param.batchName)) {
            layer.msg("优惠批次名称不能为空");
            return false;
        }
        if (zmnUtil.isEmptyNull(param.showName)) {
            layer.msg("优惠批次展示名称不能为空");
            return false;
        }
        if (zmnUtil.isEmptyNull(param.couponDesc)) {
            layer.msg("优惠劵描述不能为空");
            return false;
        }
        // 内部券,外部券判断
        if (param.couponType == 1) { // 内部券
            param.coupPlat = null;
        } else { // 外部券
            if (param.coupPlat == 1) {  // 美团劵
                if (zmnUtil.isEmptyNull(param.salePrice)) {
                    layer.msg("美团券的优惠券价格不能为空");
                    return false;
                }
            } else if (param.coupPlat == 2) {  // 支付宝无资金券

            } else {
                layer.msg("外部券类型不能为空");
                return false;
            }
        }

        // 领取条件
        if (zmnUtil.isEmptyNull(param.number) && zmnUtil.isEmptyNull(param.allNumber)) {
            layer.msg("批次优惠券总数不能为空");
            return false;
        }
        if (zmnUtil.isEmptyNull(param.receiveNumber)) {
            layer.msg("优惠券个人领取数量不能为空");
            return false;
        }

        if (zmnUtil.isEmptyNull(param.issueTime)) {
            layer.msg("优惠券发放日期不能为空");
            return false;
        }

        // 使用条件
        if (zmnUtil.isEmptyNull(param.expiryType)) {
            layer.msg("使用有效期不能为空");
            return false;
        }

        if (param.expiryType == 1 && zmnUtil.isEmptyNull(param.startAndEndDate)) {
            layer.msg("使用有效期不能为空");
            return false;
        }
        if (param.expiryType == 2 && zmnUtil.isEmptyNull(param.tempEffectiveDays)) {
            layer.msg("固定时长领取后有效期不能为空");
            return false;
        }
        // 折扣判断
        if (param.preferentialType == 1 && zmnUtil.isEmptyNull(param.preferentialDiscountValue)) {
            layer.msg("优惠券折扣不能为空");
            return false;
        }
        // 满减面额
        if (param.preferentialType == 2 && zmnUtil.isEmptyNull(param.preferentialValue)) {
            layer.msg("订单金额面额条件不能为空");
            return false;
        }

        // 订单金额满多少元使用条件
        if (zmnUtil.isEmptyNull(param.condition)) {
            layer.msg("订单金额满减条件不能为空");
            return false;
        }

        if (!param.configType) {
            layer.msg("优惠劵公司分摊规则需要选择");
            return false;
        }

        if (!param.channelConfigType) {
            layer.msg("优惠劵渠道分摊规则需要选择");
            return false;
        }

        if (!param.serverType) {
            layer.msg("优惠劵品类需要选择");
            return false;
        }

        if (!param.cityType) {
            layer.msg("优惠劵城市需要选择");
            return false;
        }

        if (!param.channelType) {
            layer.msg("优惠劵渠道需要选择");
            return false;
        }
        if (!param.companyType) {
            layer.msg("优惠劵公司需要选择");
            return false;
        }

        // 美团劵判断下销售价格

        return true;
    };

    /**
     * 内部劵 外部劵
     */
    form.on('radio(couponType)', function (data) {
        if (data.value == 1) { //  内部券
            $("#coupPlatDiv").attr("style", "display:none;");
            // $("#coupPlat").attr("lay-verify", "");
            $("#coupPlat").val("");
            form.render("select");
            //  内部券取消售价设置
            // $("#salePrice").attr("lay-verify", "");
        } else {
            $("#coupPlatDiv").attr("style", "display:block;");
            // $("#coupPlat").attr("lay-verify", "required");
        }
    });


    /**
     *优惠卷使用有效期
     */
    form.on('radio(expiryType)', function (data) {
        $("#startAndEndDate").val(null);
        $("#tempEffectiveDays").val(null);
        // 1固定期限 2 固定时长
        if (data.value == 2) {
            // $("#startAndEndDateDiv").find($("input[name='startAndEndDate']")).attr("lay-verify", "");
            // $("#tempEffectiveDaysDiv").find($("input[name='tempEffectiveDays']")).attr("lay-verify", "required");

            $("#startAndEndDateDiv").attr("style", "display:none;");
            $("#tempEffectiveDaysDiv").attr("style", "display:block;");
        } else {
            // $("#startAndEndDateDiv").find($("input[name='startAndEndDate']")).attr("lay-verify", "required");
            //   $("#tempEffectiveDaysDiv").find($("input[name='tempEffectiveDays']")).attr("lay-verify", "");
            $("#startAndEndDateDiv").attr("style", "display:block;");
            $("#tempEffectiveDaysDiv").attr("style", "display:none;");
        }
    });


    /**
     *优惠卷方式
     */
    form.on('radio(preferentialType)', function (data) {
        $("#preferentialValue").val(null);
        $("#preferentialCountValue").val(null);
        if (data.value != 2) {
            $("#preferentialValueDiv").attr("style", "display:none;");
            $("#coupDiscountDiv").attr("style", "display:block;");
            // $("#unit").prev().find($("input[name^='preferentialValue']")).attr("lay-verify","required|coupDiscount");
        } else {
            $("#preferentialValueDiv").attr("style", "display:block;");
            $("#coupDiscountDiv").attr("style", "display:none;");
            // $("#unit").prev().find($("input[name^='preferentialValue']")).attr("lay-verify","required|amount");
        }
        form.render();
    });

    /**
     *公司分摊规则
     */
    form.on('radio(configType)', function (data) {
        if (data.value == 1) {
            $("#setConfigDiv").attr("style", "display:none;");
            //$("#setConfigProfitDiv").attr("style", "display:block;");
            // $("#setConfigDiv").hide();
        } else {
            $("#setConfigDiv").attr("style", "display:block;");
            // $("#setConfigProfitDiv").attr("style", "display:none;");
            // $("#setRatioEventSpan").show();
        }
    });

    /**
     *渠道分摊规则
     */
    form.on('radio(channelConfigType)', function (data) {
        if (data.value == 1) {
            $("#setChannelConfigDiv").attr("style", "display:none;");
            //$("#setConfigProfitDiv").attr("style", "display:block;");
            // $("#setConfigDiv").hide();
        } else {
            $("#setChannelConfigDiv").attr("style", "display:block;");
            // $("#setConfigProfitDiv").attr("style", "display:none;");
            // $("#setRatioEventSpan").show();
        }
    });


    table.on('tool(demoEvent)', function (obj) {
        var data = obj.data;
        if (obj.event === 'setSign') {
            layer.prompt({
                formType: 2
                , title: '修改 ID 为 [' + data.id + '] 的用户签名'
                , value: data.sign
            }, function (value, index) {
                layer.close(index);

                //这里一般是发送修改的Ajax请求

                //同步更新表格和缓存对应的值
                obj.update({
                    sign: value
                });
            });
        }
    });

    $(document).on('mouseover', '#setRatioEventHelp1,#setRatioEventHelp2', function () {
        let setRatioEventHelpTPL = document.getElementById('setRatioEventHelpTPL');
        layer.open({
            type: 1,//这就是定义窗口类型的属性
            title: "",
            shadeClose: true,
            shade: 0.3,
            offset: "20%",
            shadeClose: false,
            area: ['50%', '70%'],
            content: setRatioEventHelpTPL.innerHTML
        });
    });

    $(document).on('click', '#setRatioEventSpan', function () {
        let apportionRateJson = $("#apportionRate").val();
        let addApportionContent = document.getElementById('addApportionContent');
        let apportionRate = JSON.parse(apportionRateJson);
        laytpl(addApportionContent.innerHTML).render(apportionRate, function (html) {
            // console.log(html);
            var contentl;
            var coupBatch = json.coupBatch;
            var index = layer.open({
                title: "公司比例分摊配置"
                , content: html
                , btn: ['确定']
                , btnAlign: 'c'
                , area: ['50%', '50%']
                , success: function () {
                    $(".apportionRateVal").each(function () {
                        var id = this.id;
                        if (id == 'headOfficeRate') {
                            if (coupBatch.headOfficeRate) {
                                this.value = coupBatch.headOfficeRate;
                            }
                        }
                        if (id == 'infoCompanyRate') {
                            if (coupBatch.infoCompanyRate) {
                                this.value = coupBatch.infoCompanyRate;
                            }
                        }
                        if (id == 'masterRate') {
                            if (coupBatch.masterRate) {
                                this.value = coupBatch.masterRate;
                            }

                        }
                    });
                }
                , yes: function (index, layero) {
                    let apportionRateArrayTemp = new Array();
                    $(".apportionRateVal").each(function (index, elem) {
                        let type = $(elem).attr("data-type");
                        let value = $(elem).val();
                        if (type == 1) {
                            $("#headOfficeRate").text(value);
                            coupBatch.headOfficeRate = value;
                        } else if (type == 2) {
                            $("#infoCompanyRate").text(value);
                            coupBatch.infoCompanyRate = value
                        } else {
                            $("#masterRate").text(value);
                            coupBatch.masterRate = value;
                        }
                        apportionRateArrayTemp.push({type: parseInt(type), value: parseInt(value)});
                    });
                    $("#apportionRate").val(JSON.stringify(apportionRateArrayTemp));
                    layer.close(index);
                }
            });
        });
    });


    $(document).on('click', '#setChannelRatioEventSpan', function () {
        let apportionRateJson = $("#apportionChannelRate").val();
        let addApportionContent = document.getElementById('addChannelApportionContent');
        let apportionRate = JSON.parse(apportionRateJson);
        laytpl(addApportionContent.innerHTML).render(apportionRate, function (html) {
            // console.log(html);
            var contentl;
            var coupBatch = json.coupBatch;
            var index = layer.open({
                title: "渠道比例分摊配置"
                , content: html
                , btn: ['确定']
                , btnAlign: 'c'
                , area: ['30%', '25%']
                , success: function () {
                    if (coupBatch.channelRate) {
                        $(".channelRateVal").val(coupBatch.channelRate);
                    }
                }
                , yes: function (index, layero) {
                    let apportionRateArrayTemp = new Array();
                    $("#channelRate").text($(".channelRateVal").val());
                    coupBatch.channelRate = $(".channelRateVal").val();
                    apportionRateArrayTemp.push({type: 4, value: parseInt($(".channelRateVal").val())});
                    $("#apportionChannelRate").val(JSON.stringify(apportionRateArrayTemp));
                    layer.close(index);
                }
            });
        });
    });

    /**
     * 城市设置
     */
    $(document).on('click', '#setCityConfigBtn', function () {
        var coupBatch = json.coupBatch;
        //  alert(coupBatch.batchId);
        // zmnLayUtil.openIframeCustom(layer, "/coup/batch/addEditCityView.action ? batchId=" + coupBatch.batchId, {
        //     shade: 1,
        //     area: ['80%', '80%']
        // });
        var url;
        if (coupBatch.batchId) {
            url = "/coup/batch/addEditCityView?batchId=" + coupBatch.batchId
            if (!zmnUtil.isEmptyNull(json.coupBatch.cityIds)) {
                url = url + "&selectCityIds=" + json.coupBatch.cityIds;
            }
        } else {
            url = "/coup/batch/addEditCityView";
            if (!zmnUtil.isEmptyNull(json.coupBatch.cityIds)) {
                url = url + "?selectCityIds=" + json.coupBatch.cityIds;
            }
        }
        layer.open({
            type: 2,
            content: url,
            area: ['80%', '80%'],
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                // debugger;
                var selectCityIds = window["layui-layer-iframe" + index].json.cityIds;
                // alert(JSON.stringify(selectCityIds));
                // 业务逻辑
                json.coupBatch.cityIds = selectCityIds;

                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
            },
            cancel: function () {
                //return false 开启该代码可禁止点击该按钮关闭
            }
        });

    });


    $(document).on('click', '#setServerTypeConfigBtn', function () {
        /*batchId=" + coupBatch.batchId*/
        var url = "/coup/batch/querytServerClassify.action?";
        if (json.coupBatch.batchId != null) {
            url += "batchId=" + json.coupBatch.batchId + "&";
        }

        if (json.coupBatch.servCategIds != null) {
            url += "servCategIds=" + json.coupBatch.servCategIds + "&";
        }
        if (json.coupBatch.categOneIds != null) {
            url += "categOneIds=" + json.coupBatch.categOneIds + "&";
        }
        if (json.coupBatch.categIds != null) {
            url += "categIds=" + json.coupBatch.categIds + "&";
        }
        if (json.coupBatch.productIds != null) {
            url += "productIds=" + json.coupBatch.productIds + "&";
        }
        if (json.coupBatch.status != 2){
            layer.open({
                type: 2,
                content: url,
                data: {
                    'batchId': json.coupBatch.batchId,
                    'servCategIds': servCategIds,
                    'categOneIds': categOneIds,
                    'categIds': categIds,
                    'productIds': productIds
                },
                area: ['80%', '80%'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    json.coupBatch.servCategIds = window["layui-layer-iframe" + index].json.servCategIds;
                    json.coupBatch.categOneIds = window["layui-layer-iframe" + index].json.categOneIds;
                    json.coupBatch.categIds = window["layui-layer-iframe" + index].json.categIds;
                    json.coupBatch.productIds = window["layui-layer-iframe" + index].json.productIds;

                    console.log(json.coupBatch.categIds);
                    layer.close(index);
                },
                btn2: function (index, layero) {
                    layer.close(index);
                },
                cancel: function () {
                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
        } else {
            layer.open({
                type: 2,
                content: url,
                data: {
                    'batchId': json.coupBatch.batchId,
                    'servCategIds': servCategIds,
                    'categOneIds': categOneIds,
                    'categIds': categIds,
                    'productIds': productIds
                },
                area: ['80%', '80%'],
                btn: ['取消'],
                btn1: function (index, layero) {
                    layer.close(index);
                },
                cancel: function () {
                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
        }

    });

    /**
     * 百分控制
     */
    $(document).on('input propertychange', '.apportionRateVal', function () {
        let val = parseInt($(this).val());
        if (isNaN(val)) {
            val = 0;
        }
        if (val < 0) {
            $(this).val(0);
            val = 0;
        }
        let currentType = $(this).attr("data-type");
        let otherRate = 0;
        $(".apportionRateVal").each(function (index, elem) {
            let type = parseInt($(elem).attr("data-type"));
            if (type != 1 && type != currentType) {
                otherRate += parseInt($(elem).val());
            }
        });
        let headOfficeRate = $("input[data-type='1'].apportionRateVal");
        if (val + otherRate > 100) {
            $(this).val(100 - otherRate);
            headOfficeRate.val(0);
        } else {
            headOfficeRate.val(100 - otherRate - val);
        }
    });


    /**
     * 描述: 优惠券使用时间初始化
     **/
    layDate.render({
        elem: '#startAndEndDate',
        format: 'yyyy-MM-dd HH:mm:ss',
        type: 'datetime',
        range: true
    });
    /**
     * 描述: 发放有效期时间初始化
     **/
    layDate.render({
        elem: '#issueTime',
        format: 'yyyy-MM-dd HH:mm:ss',
        type: 'datetime',
        range: true
    });


    /**
     * 优惠批次领取数量监听
     */
    $("#number").blur(function () {
        var receiveNumber = $("#number").val();
        if (receiveNumber && $("#allNumber").get(0).checked) {
            // $("#number").attr("lay-verify", "required|amount|max_2500");
            $('#allNumber').removeAttr('checked');
            form.render();
        }
    });
    $("#preferentialDiscountValue").keyup(function () {
        var str = $("#preferentialDiscountValue").val();
        // str = str.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        // if(str>10){
        //     st
        // }
        var len1 = str.substr(0, 1);
        var len2 = str.substr(1, 1);
        //如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 == 0 && len2 != ".") {
            str = str.substr(1, 1);
        }
        //第一位不能是.
        if (len1 == ".") {
            str = "";
        }
        //限制只能输入一个小数点
        if (str.indexOf(".") != -1) {
            var str_ = str.substr(str.indexOf(".") + 1);
            if (str_.indexOf(".") != -1) {
                str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
            }
        }
        //正则替换，保留数字和小数点
        str = (str.match(/^\d*(\.?\d{0,1})/g)[0]) || null
        if (str > 10) {
            str = 10;
        }
        $("#preferentialDiscountValue").val(str);
    });

    /**
     * 面额
     */
    $("#preferentialValue").keyup(function () {
        var str = $("#preferentialValue").val();
        str = str.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        str = str.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
        if (str.indexOf(".") < 0 && str != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
            str = parseFloat(str);
        }
        $("#preferentialValue").val(str);
    });


    /**
     * 订单金额满多少可用
     */
    $("#condition").keyup(function () {
        var str = $("#condition").val();
        str = str.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        str = str.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
        if (str.indexOf(".") < 0 && str != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
            str = parseFloat(str);
        }
        $("#condition").val(str);
    });


    /**
     * 优惠券售价
     */
    $("#salePrice").keyup(function () {
        var str = $("#salePrice").val();
        str = str.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        str = str.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
        if (str.indexOf(".") < 0 && str != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
            str = parseFloat(str);
        }
        $("#salePrice").val(str);
    });


    /**
     * 总量
     */
    form.on('checkbox(allNumber)', function (data) {
        if ($("#allNumber").get(0).checked) {
            $("#number").attr("lay-verify", "");
            $("#number").val("");
        } else {
            $("#number").attr("lay-verify", "required|amount|max_2500");
        }
        //  form.render();
    });

    var updateInit = function () {
        var coupBatch = json.coupBatch;
        //console.log(coupBatch);
        // 优惠券基本信息
        baseBatchInfo(coupBatch);
        // 优惠批次领取条件
        baseBatchReceive(coupBatch);
        // 优惠批次使用条件
        baseBatchUse(coupBatch);
        // 成本分摊
        baseShareReceive(coupBatch);
        // 使用范围
        baseUseRange(coupBatch);

    }();

    /**
     * 优惠批次基本信息
     */
    function baseBatchInfo(coupBatch) {
        // var checked = $("input[name='couponType']:checked").val();
        var couponType = coupBatch.couponType;
        if (couponType == 2) {
            $("#coupPlatDiv").attr("style", "display:block;");
            // $("coupPlat").attr("lay-verify", "required");
        } else {
            $("#coupPlatDiv").attr("style", "display:none;");
            // $("coupPlat").attr("lay-verify", "");
        }
        if (coupBatch.couponType) {
            coupBatch.couponType = coupBatch.couponType.toString();
        }
        // 优惠券基本信息
        form.val("act-base-form", coupBatch);
    }

    /**
     * 优惠批次领取条件
     */
    function baseBatchReceive(coupBatch) {
        if (coupBatch.issueTimeBegin && coupBatch.issueTimeEnd) {
            coupBatch.issueTime = zmnUtil.createTime(coupBatch.issueTimeBegin) + " - " + zmnUtil.createTime(coupBatch.issueTimeEnd);
        }
        if (coupBatch.redeemCodeGenerate) {
            coupBatch.redeemCodeGenerate = coupBatch.redeemCodeGenerate.toString();
        }
        if (coupBatch.allNumber == 0) {
            coupBatch.allNumber = coupBatch.allNumber.toString();
            //  $("#number").attr("lay-verify", "");
            $("#number").val("");
        }
        // 优惠券基本信息
        form.val("act-base-receive-form", coupBatch);
    }

    /**
     * 优惠批次使用条件
     */
    function baseBatchUse(coupBatch) {

        if (coupBatch.expiryType) {
            //使用有效期
            if (coupBatch.expiryType == 1) {
                $("#startAndEndDateDiv").attr("style", "display:block;");
                coupBatch.startAndEndDate = zmnUtil.createTime(coupBatch.usefulLifeBegin) + " - " + zmnUtil.createTime(coupBatch.usefulLifeEnd);
            } else if (coupBatch.expiryType == 2) {
                $("#tempEffectiveDaysDiv").attr("style", "display:block;");
            } else {
                $("#startAndEndDateDiv").attr("style", "display:none;");
                $("#tempEffectiveDaysDiv").attr("style", "display:none;");
            }

            //优惠方式
            if (coupBatch.preferentialType == 2) {
                $("#coupDiscountDiv").attr("style", "display:none;");
                $("#preferentialValueDiv").attr("style", "display:block;");
            } else if (coupBatch.preferentialType == 1) {
                $("#coupDiscountDiv").attr("style", "display:block;");
                $("#preferentialValueDiv").attr("style", "display:none;");
            } else {
                $("#coupDiscountDiv").attr("style", "display:none;");
                $("#preferentialValueDiv").attr("style", "display:none;");
            }

            coupBatch.expiryType = coupBatch.expiryType.toString();
            coupBatch.tempEffectiveDays = coupBatch.effectiveDays.toString();
            if (coupBatch.preferentialType == 1) {
                coupBatch.preferentialDiscountValue = coupBatch.preferentialValue / 10;
            } else {
                coupBatch.preferentialValue = coupBatch.preferentialValue / 100;
            }
            coupBatch.preferentialType = coupBatch.preferentialType.toString();
            if (coupBatch.condition) {
                coupBatch.condition = coupBatch.condition / 100;
            }
            // 数据库读出售价为0时表示没填写售价，返回null
            if (coupBatch.salePrice && coupBatch.salePrice != 0) {
                //console.log(coupBatch.salePrice)
                coupBatch.salePrice = coupBatch.salePrice / 100;
                // $("#salePrice").attr("lay-verify", "required");
            } else if (coupBatch.salePrice == 0) {
                coupBatch.salePrice = null;
                //  $("#salePrice").attr("lay-verify", "");
            }
        } else {
            var couponType = $("#couponType").val();
            var coupPlat = $("#coupPlat").val();
            // if (couponType == 1) {
            //     $("#salePrice").attr("lay-verify", "");
            // } else if (couponType == 2 && coupPlat == 1) {
            //     $("#salePrice").attr("lay-verify", "required");
            // } else {
            //     $("#salePrice").attr("lay-verify", "");
            // }
        }
        form.val("act-use-form", coupBatch);
    }


    /**
     * 优惠批次分摊规则
     */
    function baseShareReceive(coupBatch) {
        // var apportionRateArray = new Array();
        // apportionRateArray.push({type: 1, value: parseInt(coupBatch.headOfficeRate)});
        // apportionRateArray.push({type: 2, value: parseInt(coupBatch.infoCompanyRate)});
        // apportionRateArray.push({type: 3, value: parseInt(coupBatch.masterRate)});
        // apportionRateArray.push({type: 4, value: parseInt(coupBatch.channelRate)});
        // $("#apportionRate").val(JSON.stringify(apportionRateArray));

        if (coupBatch.configType) {
            coupBatch.configType = coupBatch.configType.toString();
        }

        var checked = $("input[name='configType']:checked").val();
        if (coupBatch.configType == 2) {
            $("#setConfigDiv").attr("style", "display:block;");
        } else {
            $("#setConfigDiv").attr("style", "display:none;");
        }

        if (coupBatch.channelConfigType == 2) {
            $("#setChannelConfigDiv").attr("style", "display:block;");
        } else {
            $("#setChannelConfigDiv").attr("style", "display:none;");
        }
        var ishow = json.isShow;
        if ((ishow && coupBatch.status != 2)) {
            // $("#setRatioEventSpan").prop("disabled", "false");
            $("#setRatioEventSpan").removeAttr("disabled");
        } else {
            $("#setRatioEventSpan").attr("disabled", "disabled");
            $("#setRatioEventSpan").addClass("layui-btn layui-btn-sm layui-btn-disabled");
        }

        form.val("act-cost-share-form", coupBatch);
    }

    /**
     *  使用范围
     */
    function baseUseRange(coupBatch) {
        if (coupBatch.cityType) {
            coupBatch.cityType = coupBatch.cityType.toString();
        }
        if (coupBatch.configType) {
            coupBatch.configType = coupBatch.configType.toString();
        }
        if (coupBatch.channelConfigType) {
            coupBatch.channelConfigType = coupBatch.channelConfigType.toString();
        }
        if (coupBatch.companyType) {
            coupBatch.companyType = coupBatch.companyType.toString();
        }
        if (coupBatch.channelType) {
            coupBatch.channelType = coupBatch.channelType.toString();
        }
        if (coupBatch.serverType) {
            coupBatch.serverType = coupBatch.serverType.toString();
        }

        // 渠道选择
        channelEcho(coupBatch.channelIds);
        // 公司选择
        companyEcho(coupBatch.companyIds);
        form.val("act-use-rang-form", coupBatch);
        form.val("zmn-batch-form", coupBatch);

    };

    /**
     *  渠道选择
     */
    function channelEcho(channelIds) {
        let arr = new Array();
        let selectedArray = new Array();
        let channel = json.channelType;
        $(channel).each(function (channelIndex, channelItem) {
            let channelItemNewItem = new Object();
            channelItemNewItem.name = channelItem.name;
            channelItemNewItem.value = channelItem.typeId;
            arr.push(channelItemNewItem);
            if (channelIds) {
                $(channelIds).each(function (channelIdIndex, channelId) {
                    if (channelItemNewItem.value == channelId) {
                        //选中渠道
                        selectedArray.push(channelId);
                        return false;
                    }
                });
            }
        });
        formSelects.data('channelTypeSelect', 'local', {
            arr: arr,
            linkage: false
        });
        formSelects.value('channelTypeSelect', selectedArray);
    }

    /**
     *  公司选择
     */
    function companyEcho(companyIds) {
        let arr = new Array();
        let selectedArray = new Array();
        let company = json.company;
        $(company).each(function (companyIndex, companyItem) {
            let companyCityItem = new Object();
            companyCityItem.name = companyItem.text;
            companyCityItem.value = companyItem.value;
            arr.push(companyCityItem);
            if (companyIds) {
                $(companyIds).each(function (companyIdIndex, companyId) {
                    if (companyItem.value == companyId) {
                        //选中公司
                        selectedArray.push(companyId);
                        return false;
                    }
                });
            }
        });
        formSelects.data('companyTypeSelect', 'local', {
            arr: arr,
            linkage: false
        });
        formSelects.value('companyTypeSelect', selectedArray);
    }


    /*table.on('tool(setRatioEvent)', function(obj){
        console.log(111);
        let data = obj.data;
        if(obj.event === 'setRatio'){
            console.log(111);
            console.log(obj.data);
            layer.prompt({
                formType: 2
                ,title: '修改 ID 为 ['+ data.id +'] 的用户签名'
                ,value: data.sign
            }, function(value, index){
                layer.close(index);

                //这里一般是发送修改的Ajax请求

                //同步更新表格和缓存对应的值
                obj.update({
                    sign: value
                });
            });
        }
    });*/


    /* $(document).on('click', '#couponType1', function () {
         console.log(1213);

     });
     $(document).on('click', '#couponType2', function () {

     });*/


    /*treeGrid.render({
        id: tableId
        , elem: '#' + tableId
        , url: '/system/organ/tree.action'
        , where: data
        , cellMinWidth: 100
        , idField: 'orgId'//必須字段
        , treeId: 'orgId'//树形id字段名称
        , treeUpId: 'parentId'//树形父id字段名称
        , treeShowName: 'orgName'//以树形式显示的字段
        , heightRemove: [".dHead", 10]//不计算的高度,表格设定的是固定高度，此项不生效
        , height: '100%'
        , isFilter: false
        , iconOpen: true//是否显示图标【默认显示】
        , isOpenDefault: false//节点默认是展开还是折叠【默认展开】
        , loading: true
        , method: 'post'
        , isPage: false
        , toolbar: "#zmn-table-tool"
        , cols: [[
            {type: 'checkbox',field: 'orgId', width: 50, unresize: true},
            {field: 'sort', title: '排序', width: 80, align: 'center', edit: 'text', unresize: true, sort: false,event:"editClick"},
            {field: 'orgId', title: '组织ID', width: 80, align: 'center', unresize: true, sort: false,templet:(d)=>{
                    if (d.orgId) {
                        return d.orgId;
                    } else {
                        return "--";
                    }
                }},
            {field: 'orgName',  title: '组织名称', width: 350, sort: true, unresize: true},
            {field: 'level', title: '等级', width: 80, align: 'center', unresize: true, sort: false},
            {
                field: 'type', title: '类型', width: 80, align: 'center', unresize: true, templet: function (d) {
                    return zmnEnum.ORGAN_TYPE[d.type];
                }
            },
            {field: 'companyId', title: '公司ID', width: 90, align: 'center', unresize: true, sort: false,templet:(d)=>{
                    if (d.companyId) {
                        return d.companyId;
                    } else {
                        return "--";
                    }
                }},
            {
                field: 'status', title: '状态', width: 80, align: 'center', unresize: true, templet: function (d) {
                    return zmnEnum.STATUS[d.status];
                }
            },
            {field: 'updater', title: '最近修改人/时间', width: 300, align: 'center', unresize: true,templet:function (row) {
                    return row.updater+"/"+zmnUtil.createTime(row.updateTime);
                }},
            {
                title: '操作', align: 'center'
                , templet: function (row) {
                    var html = '';
                    var nextDepartment = '<a style="color: #00a0e9" lay-text="下级组织" lay-href="/system/organ/list.action?parentId='+row.orgId+'">下级组织</a>&nbsp;&nbsp;&nbsp;&nbsp;';
                    var deparment = '<a  style="color: #00a0e9"  lay-text="部门列表" lay-href="/system/organ/departments.action?orgId='+row.orgId+'&flag=2">部门</a>&nbsp;&nbsp;&nbsp;&nbsp;';
                    var update = '<a  style="color: #00a0e9"  lay-text="修改组织" lay-href="/system/organ/detail.action?parentId='+row.parentId+'&id='+row.orgId+'&flag=1">修改</a>&nbsp;&nbsp;&nbsp;&nbsp;';
                    return nextDepartment +deparment+ update;
                }
            }
        ]]
        , parseData: function (res) {//数据加载后回调
            return res;
        }
    });*/


    //对外暴露的接口
    exports('batch_sub', {});
});
